 package statechurn;

import primitives.graph.*;
import translator.DOTWriter;
import java.io.File;

class TraceParserTest{

	public static accept(Node start, traces){
		def strings = traces.clone()
		int accepted = 0
		while(!strings.isEmpty()){
			def elem = strings.pop()
			if(start.labelCount(elem) > 1) println "NONDETERMINISM FAILURE: $start has multiple transitions for $elem"
			if(start.hasTransitionWithLabel(elem)){
				def tx = start.transitionWithLabel(elem)
				start = tx.destinationNode
				accepted++;
			}else{
				return [false,strings + [elem],accepted]
			}
		}
		return [true,[],accepted]
	}

    	public static compareTraces(remainder, trace){
		def ret = []
		while(!trace.isEmpty()){
			def cur = trace.pop();
			
			if(!remainder.isEmpty()){
				def rem = remainder.pop();
				if(rem.equals(cur)){
					ret.add("\033[31m$cur")
				}else{
					ret.add("\033[32m$cur")
				}
			}else{
				ret.push("\033[0m$cur")
			}
			
		}
		return ret.reverse()
	}
        
	public static void main(String[] args){
		ArrayList<String> lines = new ArrayList<String>();
		def f = new File(args[0])
		
		def traces = TraceParser.getTraces((String[]) (f.readLines().toArray()))
		def tp = new TraceParser();
		tp.debug = false;
		tp.loadPTAFromTraces(new File(args[0]));
		def g = tp.doKTails()
		def start = null
		g.getNodes().each{
			if(it.label.equals("Start")) start = it
		}
		if(start == null){
			println "ERROR: start node couldn't be found"
			System.exit(-1);
		}
		
		print "Minimised, testing traces"
		def count = 0
		def wrong = 0
		def right = 0
		traces.each{  trace ->
			if(trace != [] && !trace.isEmpty()){

				def (res,rem,accepted) = accept(start, trace)
				if(!res){
					wrong++
					println "Minimised machine failed to accept a sequence after accepting $accepted inputs"
		
					

					println compareTraces(rem.reverse(), trace.reverse())
					
					println "\033[0m"
				
				    
				}else{right++}
				count++
			}
		}
		println "Tests complete. Of $count traces, $right were accepted and $wrong not accepted"
		
	}
	


}